package com.puhui.lib.utils

import android.util.SparseArray
import android.view.View
import com.puhui.lib.R

/**
 * Description:
 * Data：2019/8/29-16:23
 * Author: Tony
 */
object ClickUtils {
    /**
     * 保存上一次点击时间
     */
    private val lastClickTimes = SparseArray<Long>()

    /**
     * 检测是否重复点击
     */
    @JvmStatic
    @JvmOverloads
    fun checkClick(id: Int, duration: Int = 800): Boolean {
        val lastTime = lastClickTimes[id]
        val thisTime = System.currentTimeMillis()
        lastClickTimes.put(id, thisTime)
        return lastTime == null || thisTime - lastTime > duration
    }

//    @JvmStatic
//    @JvmOverloads
//    fun checkClick(v: View, duration: Int = 800): Boolean {
//        val tag = v.getTag(R.id.key_last_click_time)
//        val currentTimeMillis = System.currentTimeMillis()
//        v.setTag(R.id.key_last_click_time, currentTimeMillis)
//        return if (tag is Long) currentTimeMillis - tag > duration
//        else true
//    }
}

/**
 * View的点击事件扩展函数
 */
fun View.setClick(block: () -> Unit) {
    setOnClickListener {
        if (ClickUtils.checkClick(id)) {
            block()
        }
    }
}